// 导入NestJS的异常过滤器和HttpException
import {
  ArgumentsHost,
  ExceptionFilter,
  HttpException,
  Catch,
} from '@nestjs/common';
// 导入express的Request和Response
import type { Request, Response } from 'express';

/**
 * 全局异常拦截器
 */
@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
  // 实现ExceptionFilter接口的catch方法
  catch(exception: HttpException, host: ArgumentsHost) {
    // 获取当前请求的上下文
    const ctx = host.switchToHttp();
    // 获取响应对象
    const response = ctx.getResponse<Response>();
    // 获取请求对象
    const request = ctx.getRequest<Request>();
    // 获取异常的状态码
    const status = exception.getStatus();
    // 设置响应的状态码和响应体
    response.status(status).json({
      success: false,
      time: new Date(),
      data: exception.message,
      status,
      path: request.url,
    });
  }
}
